import { Injectable } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { post } from "superagent"
import * as moment from "moment"
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class WorkloadService {
    constructor(
        public readonly prismaService: PrismaService
    ) {
        this.setOptions()
    }
    private readonly cookies = "pgv_pvid=274336464; RK=OnRco4kbTA; ptcz=9eaaa84a55b59d605d64ba0a197528839c1fa1043188266e5c0d45a05cc42284; pac_uid=1_1750354949; fqm_pvqid=a64600b8-4662-46e9-b4ea-82157408559b; _ga=GA1.2.500472363.1656660447; o_cookie=1750354949; iip=0; _clck=3920665689|1|fl5|0; eas_sid=c1R629k7p495C5L4Q574t6G3n5; _qimei_q36=; _qimei_h38=8f9576cf419b9743e74cd0260200000d817b01; o2_uin=1750354949; user_name=Abbbbb; ibox_auth_user_name=Abbbbb; user_id=100000009898; ibox_auth_user_id=100000009898; source=unify; ibox_auth_source=unify; user_token=b26f70254c08e8f19d798df0ffbd4b3c8729a87f72e9f6de5e7ac44560a74924befee3038084b094edc41636b7165da22b64331e2191f9cd1ce8717e1a8fa7159d276b787268ef0fcca89ff08facb8efe74b460a8f13b4d0fc6109e4203f94468c0107ec07be4c060b2e68925be19c7ebf87b13a6367bef0918194026379fd678858e0d54be617fdeaf2dd90d2462353298ea1fa89758ec334ecf6d952e64ad96b1a23ccb8d74c4066cd2f8aebde0ea53bc5c23b8514d6a2fa22532847298f9db79c011cf6f3a674f5499e43598023b527175e0cc5337cad79697fbdd8ef357a; ibox_auth_user_token=b26f70254c08e8f19d798df0ffbd4b3c8729a87f72e9f6de5e7ac44560a74924befee3038084b094edc41636b7165da22b64331e2191f9cd1ce8717e1a8fa7159d276b787268ef0fcca89ff08facb8efe74b460a8f13b4d0fc6109e4203f94468c0107ec07be4c060b2e68925be19c7ebf87b13a6367bef0918194026379fd678858e0d54be617fdeaf2dd90d2462353298ea1fa89758ec334ecf6d952e64ad96b1a23ccb8d74c4066cd2f8aebde0ea53bc5c23b8514d6a2fa22532847298f9db79c011cf6f3a674f5499e43598023b527175e0cc5337cad79697fbdd8ef357a"
    private options = new Map<number, {
        project: number,
        ugc_type: string,
        source: number,
        source_type: number,
        source_desc: string
    }>();
    private async init() {
        const currentTime = moment();
        const startTime = moment().startOf('day').hour(1);
        while (startTime.isBefore(currentTime)) {
            await this.scheduleWork(startTime).then(e => {
                console.log(e.id, e.works.length, startTime.format("YYYY-MM-DD HH:mm:ss"))

            });
            startTime.add(1, 'hour');
        }
    }
    private setOptions() {
        this.getOptions().then(({ body }) => {
            const { data } = body;
            for (const item of data) {
                const { source } = item;
                this.options.set(source, item);
            }
            this.init();
        })
    }
    public getTime(currentTime: moment.Moment) {
        const previousHourStart = currentTime.clone().startOf('hour').subtract(1, 'hour');
        const previousHourEnd = previousHourStart.clone().endOf('hour');
        const start_time = previousHourStart.format('YYYY-MM-DD HH:mm:ss');
        const end_time = previousHourEnd.format('YYYY-MM-DD HH:mm:ss');
        return {
            start_time,
            end_time,
            gte: previousHourStart.toDate(),
            lte: previousHourEnd.toDate()
        }
    }

    @Cron("0 * * * *")
    private async scheduleWork(currentTime: moment.Moment = moment()) {
        const {
            start_time,
            end_time,
            gte,
            lte
        } = this.getTime(currentTime)
        const find = await this.prismaService.workForHour.findFirst({
            where: {
                date: {
                    gte,
                    lte
                }
            },
            include: {
                works: true
            }
        })
        if (!!find) return find
        const { body } = await this.getWork(start_time, end_time);
        const { data } = body;
        const res = await this.prismaService.workForHour.create({
            data: {
                date: gte,
                works: {
                    createMany: {
                        data: data.details.map(({
                            handler,
                            total_num,
                            evil_num,
                            pass_num,
                            other_num,
                            content_type,
                            source
                        }) => {
                            return {
                                handler,
                                total_num,
                                evil_num,
                                pass_num,
                                other_num,
                                content_type,
                                source,
                                source_type: this.options.get(source).source_type || -1,
                                source_desc: this.options.get(source).source_desc || "undefined"
                            }
                        })
                    }
                }
            },
            include: {
                works: true
            }
        })
        return res;
    }

    public getOptions() {
        return post("https://ace.qq.com/mtp_esb/cgi/reviews/sources?service_id=2388&game_id=690841190&ugc_type=&audit_type=1")
            .send({
                "game_id": 690841190,
                "ugc_type": "",
                "audit_type": 1
            }).set("Cookie", this.cookies).set("Content-Type", "application/json")
    }

    public getWork(start_time: string, end_time: string) {
        console.log(start_time, end_time)
        return post("https://ace.qq.com/mtp_esb/cgi/reviews/stat/query?service_id=2388&game_id=690841190&content_type=&audit_type=1")
            .send({
                "game_id": 690841190,
                "handler": "",
                start_time,
                end_time,
                "content_type": "",
                "source": 0,
                "audit_type": 1,
                "statics_dimension": ""
            }).set("Cookie", this.cookies).set("Content-Type", "application/json")
    }

    public getAllWork(end_time: string) {
        const gte = moment().startOf("day").toDate()
        const lte = moment(end_time, "YYYY-MM-DD HH:mm:ss").toDate()
        return this.prismaService.workForHour.findMany({
            where: {
                date: {
                    gte,
                    lte
                }
            },
            include: {
                works: true
            }
        })
    }


    private async getTypes() {
        const posts = [{
            "game_id": 8888,
            "ugc_type": "pic",
            "audit_type": 1
        }, {
            "game_id": 8888,
            "ugc_type": "rich-text",
            "audit_type": 1
        }, {
            "game_id": 8888,
            "ugc_type": "pic",
            "audit_type": 2
        }, {
            "game_id": 8888,
            "ugc_type": "rich-text",
            "audit_type": 2
        }, {
            "game_id": 8888,
            "ugc_type": "text"
        }]
        const result = [];
        const baseUrl = "https://ace.qq.com/mtp_esb/cgi/reviews/sources?service_id=2388";
        for (const options of posts) {
            let url = baseUrl;
            for (const key in options) {
                url += `&${key}=${options[key]}`
            }
            await post(url)
                .set("Cookie", this.cookies).set("Content-Type", "application/json")
                .send(options).then(({ body: { data } }) => {
                    for (const item of data) {
                        result.push(item);
                    }
                })
        }
        return result;

        //图片审核fetch
        // post("https://ace.qq.com/mtp_esb/cgi/reviews/sources?service_id=2388&game_id=8888&ugc_type=pic&audit_type=1")
        //     .set("Cookie", this.cookies).set("Content-Type", "application/json")
        //     .send({
        //         "game_id": 8888,
        //         "ugc_type": "pic",
        //         "audit_type": 1
        //     })

        // //富文本审核fetch
        // post("https://ace.qq.com/mtp_esb/cgi/reviews/sources?service_id=2388&game_id=8888&ugc_type=rich-text&audit_type=1")
        //     .set("Cookie", this.cookies).set("Content-Type", "application/json")
        //     .send({
        //         "game_id": 8888,
        //         "ugc_type": "rich-text",
        //         "audit_type": 1
        //     })

        // //文本审核fetch
        // post("https://ace.qq.com/mtp_esb/cgi/reviews/audit_types?service_id=2388&game_id=8888&ugc_type=text")
        //     .set("Cookie", this.cookies).set("Content-Type", "application/json")
        //     .send({
        //         "game_id": 8888,
        //         "ugc_type": "text"
        //     })

    }
    public async getWorkCount() {
        const baseURL = "https://ace.qq.com/mtp_esb/cgi/reviews/tasks/count/v2?service_id=2388&game_id=8888"
        const types = await this.getTypes()
        // ugc_type = pic & evil_type=0 & audit_type=1 & audit_once_evil_type=0"
        const result = []
        const start_time = moment().startOf("day").format("YYYY-MM-DD HH:mm:ss")
        const end_time = moment().endOf("day").format("YYYY-MM-DD HH:mm:ss")
        for (const options of types) {
            let url = baseURL;
            for (const key in options) {
                url += `&${key}=${options[key]}`
            }
            await post(url)
                .set("Cookie", this.cookies).set("Content-Type", "application/json")
                .send({
                    "game_id": 8888,
                    "ugc_type": options["ugc_type"],
                    "source": options["source"],
                    "scene": 0,
                    "data_scene": "",
                    "evil_type": 0,
                    start_time,
                    end_time,
                    "audit_type": 1,
                    "account": "",
                    "last_audit_result": 0,
                    "content_id": "",
                    "precise": false,
                    "audit_once_evil_type": 0,
                    "language": ""
                }).then(({ body }) => {
                    result.push({
                        ...options,
                        count: body.data.count
                    })
                    console.log(result[result.length - 1])
                })
        }
        return result;
        // a = {
        //     project: 0,
        //     ugc_type: 'rich-text',
        //     source: 453099,
        //     source_type: 0,
        //     source_desc: '默认_数据渠道'
        // }

        //search
        // await fetch("https://ace.qq.com/mtp_esb/cgi/reviews/tasks/count/v2?service_id=2388&game_id=8888&ugc_type=pic&evil_type=0&audit_type=1&audit_once_evil_type=0", {
        //     "credentials": "include",
        //     "headers": {
        //         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:125.0) Gecko/20100101 Firefox/125.0",
        //         "Accept": "application/json, text/plain, */*",
        //         "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
        //         "Content-Type": "application/json",
        //         "ibox-request-trace": "UmV2aWV3X3BpY19yZXZpZXc=",
        //         "Sec-Fetch-Dest": "empty",
        //         "Sec-Fetch-Mode": "cors",
        //         "Sec-Fetch-Site": "same-origin",
        //         "Pragma": "no-cache",
        //         "Cache-Control": "no-cache"
        //     },
        //     "referrer": "https://ace.qq.com/ibox_2378/",
        //     "body": "{\"game_id\":8888,\"ugc_type\":\"pic\",\"source\":3,\"scene\":0,\"data_scene\":\"\",\"evil_type\":0,\"start_time\":\"2024-05-01 00:00:00\",\"end_time\":\"2024-05-01 23:59:59\",\"audit_type\":1,\"account\":\"\",\"last_audit_result\":0,\"content_id\":\"\",\"precise\":false,\"audit_once_evil_type\":0,\"language\":\"\"}",
        //     "method": "POST",
        //     "mode": "cors"
        // });
    }
}
